package com.suncnpap.base.controller;




import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.app.util.common.HandlerResult;
import com.app.util.common.ResponseUtil;
import com.suncnpap.base.common.GlobaUser;
import com.suncnpap.base.common.Ticket;
import com.suncnpap.reader.model.Reader;
import com.suncnpap.system.model.Admin;

@Controller
public class RefreshTokenController {

	@RequestMapping(value="/refreshToken",method=RequestMethod.POST)
	public void login(HttpServletRequest request,HttpServletResponse response) {
		
		HandlerResult result = new HandlerResult();

		String refToken = request.getParameter("refToken");
		String token = request.getParameter("token");
		List<Object> obj=Ticket.getTicketMap().get(refToken);
		if(obj!=null){
			long nowTime=new Date().getTime();
			long oldTime=(Long)obj.get(2);
			if((nowTime-oldTime)>(60*60*1000)){//有效期 60分钟
				result.setCode(50014);
				result.setMessage("refToken失效");
			}else{
				result.put("token", Ticket.getRandom((String)obj.get(0), Ticket.getTicket(30)));
				result.put("reftoken", Ticket.getRandom((String)obj.get(0), Ticket.getTicket(30)));
				
				Object[] object = GlobaUser.getUser(token);
				if(object!=null && (object[0]+"").equals("admin")){
					GlobaUser.setGlobaUser((String)result.getMap().get("token"), (Admin)object[2]);
				}else{
					GlobaUser.setGlobaReader((String)result.getMap().get("token"), (Reader)object[2]);
					
				}
				GlobaUser.removeGlobaUser(token);
				Ticket.getTicketMap().remove(token);
			}
		}else{
			result.setCode(50008);
			result.setMessage("refToken失效");
		}
	    
	    ResponseUtil.writeJson(result, response);
	}
	
	
	
}
